package com.neo.office.server.controller.system;

import com.neo.office.server.config.data.Result;
import com.neo.office.server.domain.entity.User;
import com.neo.office.server.domain.model.LoginBody;
import com.neo.office.server.service.RoleService;
import com.neo.office.server.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "登录返回token")
    @PostMapping("/login")
    public Result login(@RequestBody LoginBody loginBody, HttpServletRequest request) {
        Result result = userService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),request);
        return result;
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/user/info")
    public User getAdminInfo(Principal principal) {
        if (principal == null) {
            return null;
        }
        String username = principal.getName();
        User user = userService.getUserByUserName(username);
        user.setPassword(null);
        user.setRoles(roleService.getRoles(user.getId()));
        return user;
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public Result logout() {
        return Result.success("注销成功！");
    }

}
